package com.gomo;

import org.ksoap2.serialization.SoapObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.gomo.R;
import com.gomo.entity.User;

public class EditUserActivity extends Activity {

	private EditText txtUserEditName;
	private EditText txtUserEditCNIC;
	private EditText txtUserEditPassport;
	private EditText txtUserEditAddress;
	private EditText txtUserEditCity;
	private EditText txtUserEditState;
	private Spinner spnrUserEditCountry;
	private EditText txtUserEditContact;
	AlertDialog alertDialog;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_edit);
		setUI();
	}

	public void buttonSignupSubmitClick(View view) {
		if (isValidate()) {
			new ParseXmlTaskUpdateUser().execute();
		}
	}

	private void setUI() {
		txtUserEditName = (EditText) findViewById(R.id.user_edit_text_name);
		txtUserEditCNIC = (EditText) findViewById(R.id.user_edit_text_cnic);
		txtUserEditPassport = (EditText) findViewById(R.id.user_edit_text_passport);
		txtUserEditAddress = (EditText) findViewById(R.id.user_edit_text_address);
		txtUserEditCity = (EditText) findViewById(R.id.user_edit_text_city);
		txtUserEditState = (EditText) findViewById(R.id.user_edit_text_province);
		spnrUserEditCountry = (Spinner) findViewById(R.id.user_edit_spinner_country);
		txtUserEditContact = (EditText) findViewById(R.id.user_edit_text_contact);
		createDialogMessage();

		new ParseXmlTaskGetUser().execute();

	}

	private void populateUI(User user) {

		try {
			txtUserEditName.setText(user.getName());
			txtUserEditCNIC.setText(user.getCNIC());
			txtUserEditPassport.setText(user.getPassportNo());
			txtUserEditAddress.setText(user.getAddress());
			txtUserEditCity.setText(user.getCity());
			txtUserEditState.setText(user.getStateProvince());
			String myString = user.getCountry();
			ArrayAdapter myAdap = (ArrayAdapter) spnrUserEditCountry
					.getAdapter();
			int spinnerPosition = myAdap.getPosition(myString);
			spnrUserEditCountry.setSelection(spinnerPosition);
			txtUserEditContact.setText(user.getContactNo());

		} catch (Exception e) {
			GlobalService.HandleException(e);
		}
	}

	private User processServiceGetUserInformation() {
		SoapService ss = new SoapService();

		String soap_method_name = getString(R.string.method_user_get);
		String soap_namespace = getString(R.string.service_namespace);
		String soap_url = getString(R.string.service_url);
		String soap_action = soap_namespace + soap_method_name;
		String android_id = Secure.getString(getBaseContext()
				.getContentResolver(), Secure.ANDROID_ID);

		SoapObject soap_object_request = new SoapObject(soap_namespace,
				soap_method_name);

		soap_object_request.addProperty("UserId", GlobalService.getUserId());
		soap_object_request.addProperty("PinCode",
				GlobalService.getUserPinCode());
		soap_object_request.addProperty("DeviceId", android_id);
		soap_object_request.addProperty("DeviceType", "2");

		SoapObject soap_object_response = ss.parseWebService(soap_action,
				soap_url, soap_object_request);
		SoapObject recordsArray = (SoapObject) soap_object_response
				.getProperty(0);

		User user = new User();
		try {
			Ksoap2ResultParser.parseBusinessObject(recordsArray.toString(),
					user);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return user;
	}

	private String processServiceUpdateUser() {

		SoapService ss = new SoapService();
		String soap_method_name = getString(R.string.method_user_update);
		String soap_namespace = getString(R.string.service_namespace);
		String soap_url = getString(R.string.service_url);
		String soap_action = soap_namespace + soap_method_name;
		String android_id = Secure.getString(getBaseContext()
				.getContentResolver(), Secure.ANDROID_ID);
		SoapObject soap_object_request = new SoapObject(soap_namespace,
				soap_method_name);
		soap_object_request.addProperty("UserId", GlobalService.getUserId()
				.toString());

		soap_object_request.addProperty("Name", txtUserEditName.getText()
				.toString());
		soap_object_request.addProperty("CNIC", txtUserEditCNIC.getText()
				.toString());
		soap_object_request.addProperty("PassportNo", txtUserEditPassport
				.getText().toString());
		soap_object_request.addProperty("Address", txtUserEditAddress.getText()
				.toString());
		soap_object_request.addProperty("City", txtUserEditCity.getText()
				.toString());
		soap_object_request.addProperty("StateProvince", txtUserEditState
				.getText().toString());
		soap_object_request.addProperty("Country", spnrUserEditCountry
				.getSelectedItem().toString());
		soap_object_request.addProperty("ContactNo", txtUserEditContact
				.getText().toString());

		soap_object_request.addProperty("PinCode", GlobalService
				.getUserPinCode().toString());
		soap_object_request.addProperty("DeviceId", android_id);
		soap_object_request.addProperty("DeviceType", "2");

		SoapObject soap_object_response = ss.parseWebService(soap_action,
				soap_url, soap_object_request);
		SoapObject recordsArray = (SoapObject) soap_object_response
				.getProperty(0);
		String soapresultid = recordsArray.getProperty("ID").toString();
		String soapresultmsg = recordsArray.getProperty("Message").toString();
		return soapresultid + "|" + soapresultmsg;
	}

	private boolean isValidate() {
		if (!GlobalService.isOnline(this)) {
			GlobalService.MessageBox("No or limited internet connection", this);
			return false;
		}
		return true;
	}

	private void createDialogMessage() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("").setCancelable(false)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		alertDialog = builder.create();
	}

	class ParseXmlTaskGetUser extends AsyncTask<Void, Void, User> {
		private final ProgressDialog dialog = new ProgressDialog(
				EditUserActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Getting user information...");
			this.dialog.show();
		}

		protected User doInBackground(Void... unused) {
			return processServiceGetUserInformation();
		}

		protected void onPostExecute(User user) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();
			populateUI(user);
		}
	}

	class ParseXmlTaskUpdateUser extends AsyncTask<Void, Void, String> {
		private final ProgressDialog dialog = new ProgressDialog(
				EditUserActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Updating user...");
			this.dialog.show();
		}

		protected String doInBackground(Void... unused) {
			return processServiceUpdateUser();
		}

		protected void onPostExecute(String soapresultmsg) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();

			String[] arrString = GlobalService.splitString(soapresultmsg, "|");
			String id = arrString[0];
			String message = arrString[1];

			if (id.equalsIgnoreCase("0")) {
				alertDialog.setMessage(message);
				alertDialog.show();
			} else {
				//Intent myIntent = new Intent(getBaseContext(),
				//		HomeActivity.class);
				finish();
				//startActivityForResult(myIntent, 0);
			}

		}
	}

}